/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.shop.web.controllers;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.shop.domain.Customer;
import org.shop.domain.Transactions;
import org.shop.service.InventoryService;
import org.shop.utils.InstanceUtils;
import org.shop.web.utils.RootController;

/**
 *
 * @author Vinnu
 */
public class BalanceUpdateController extends RootController {

    private static Logger log = Logger.getLogger(BalanceController.class);

    @Override
    protected void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String action = request.getParameter("updateBalance");
        InstanceUtils utils = new InstanceUtils();
        InventoryService service = utils.getService();

        if (action.equalsIgnoreCase("Get Details")) {
            log.info("Get Details Called...");
            String customerName = request.getParameter("customerName");
            long mobile = Long.valueOf(request.getParameter("mobile"));
            log.debug(customerName + mobile);
            Customer customer = service.findByCustomer(customerName, mobile);
            if (customer == null) {
                return;
            } else {
                Map<String, Object> balanceMap = service.getBalanceDetails(customer.getCustomer_Id());
                log.info("Balance Map:-" + balanceMap);
                balanceMap.put("Name", customerName);
                balanceMap.put("Mobile", mobile);
                request.setAttribute("MapDetails", balanceMap);
                request.getRequestDispatcher("/updateBalance.jsp").forward(request, response);

            }
        } else if (action.equalsIgnoreCase("Update Balance")) {
            String customerName = request.getParameter("customerName");
            long mobile = Long.valueOf(request.getParameter("customerPhone"));
            double updatedAmount = Double.valueOf(request.getParameter("updatedAmount").trim());
            Customer customer = service.findByCustomer(customerName, mobile);
            Transactions transactions = utils.getBalance();
            transactions.setCustomer_Id(customer);
            transactions.setPayment_Amount(updatedAmount);
            transactions.setRemaining_Balance(0.0);
            transactions.setDate(new Date());
            transactions.setPurchase_Amount(0.0);
            service.updateTransactions(transactions);
            request.setAttribute("BalanceStatus", "Balance Updated Successfully");
            request.getRequestDispatcher("/updateBalance.jsp").forward(request, response);
        }
    }
}
